﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Core.Models;
using System.Data.Entity;

namespace Core.Controllers
{
    [Authorize]
    public class DomainController : Controller
    {
        //
        // GET: /Domain/
        
        public ActionResult Index()
        {
            if (UserPermissions.HasPermission("Can Create/Delete Domain"))
            {
                return View();
            }
            else if (UserPermissions.HasPermission("Can Modify Domain"))
            {
                return RedirectToAction("Details", new { id = Session["DomainId"].ToString()});
            }
            else
                return RedirectToAction("NoPermission","Account");
        }

        //
        // POST: /BusinessUnit/BUList/

        [HttpPost]
        public JsonResult DomainList(FormCollection collection)
        {
            CoreEntities core = new CoreEntities();
            int SkipRecs = int.Parse(collection.GetValues("iDisplayStart")[0].ToString());
            int TakeCount = int.Parse(collection.GetValues("iDisplayLength")[0].ToString());
            string strSearch = collection.GetValues("sSearch")[0].ToString();
            DataTableResponse r = new DataTableResponse();
            // Needs update when paging & sorting is implemented
            List<Domain> list = core.Domains.Where(m => (m.DomainName.Contains(strSearch) && m.IsDroppedYN == "N")).OrderBy(m => m.DomainName).Skip(SkipRecs).Take(TakeCount).ToList();
            r.sEcho = collection.GetValues("sEcho")[0].ToString();
            // This query is required because the earlier query returns results for only 1 page.
            r.iTotalRecords = core.Domains.Where(m => (m.DomainName.Contains(strSearch) && m.IsDroppedYN == "N")).Count();
            r.iTotalDisplayRecords = r.iTotalRecords;
            foreach (Domain d in list)
            {
                List<string> r1 = new List<string>();
                string editurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"editlink\" title=\"{1}\" >Edit</a>", "Domain", "Edit", d.DomainId.ToString());
                string detailsurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"detailslink\" title=\"{1}\" >Details</a>", "Domain", "Details", d.DomainId.ToString());
                string deleteurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"deletelink\" title=\"{1}\" >Delete</a>", "Domain", "Delete", d.DomainId.ToString());
                r1.Add(editurl + detailsurl + deleteurl);
                r1.Add(d.DomainName);
                r1.Add(Core.Tools.YesNo(d.IsMultiBUYN));
                r1.Add(Core.Tools.YesNo(d.EnableSelfRegisterYN));
                r1.Add(String.Format("{0:g}", d.ModifiedDT));
                r1.Add(d.ModifiedByName);
                r.aaData.Add(r1);
            }
            return Json(r);
        }

        //
        // GET: /Domain/Details/5

        [Permission("Can Create/Delete Domain, Can Modify Domain")]
        public ActionResult Details(Guid id)
        {
            CoreEntities domainbu = new CoreEntities();
            Domain domain = domainbu.Domains.First(d => d.DomainId == id);
            domain.PrimaryBusinessUnit = domain.BusinessUnits.First(m => m.BusinessUnitId == domain.PrimaryBU);
            BusinessUnit bu = domain.PrimaryBusinessUnit;
            BUHelper.PopulatePlugins(domainbu, ref bu, true);
            ViewBag.MobileTheme = domain.MobileThemeId.HasValue ? domainbu.Themes.First(m => m.ThemeId == domain.MobileThemeId).Name : "";
            return View(domain);
        }

        //
        // GET: /Domain/Create

        [Permission("Can Create/Delete Domain")]
        public ActionResult Create()
        {
            Domain domain = new Domain();
            domain.DomainId = Guid.NewGuid();
            BusinessUnit bu = new BusinessUnit();
            bu.BusinessUnitId = Guid.NewGuid();
            bu.MainAddressId = Guid.NewGuid();
            bu.Address = new Address();
            bu.Address.AddressId = (Guid)bu.MainAddressId;
            bu.DomainId = domain.DomainId;
            domain.BusinessUnits.Add(bu);
            domain.PrimaryBU = bu.BusinessUnitId;
            domain.PrimaryBusinessUnit = bu;

            CoreEntities core = new CoreEntities();
            BUHelper.PopulatePlugins(core, ref bu, false);
            ViewBag.Themes = core.Themes.Where(m => m.IsForMobileYN == "N").ToList();
            ViewBag.MobileThemes = core.Themes.Where(m => m.IsForMobileYN == "Y").ToList();
            return View(domain);
        } 

        //
        // POST: /Domain/Create

        [HttpPost]
        [Permission("Can Create/Delete Domain")]
        public ActionResult Create(Domain domain, FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                if (ModelState.IsValid)
                {
                    // Update the domain record
                    domain.DomainId = Guid.NewGuid();
                    domain.IsDroppedYN = "N";
                    domain.CreateDT = DateTime.Now;
                    domain.CreatedById = (Guid)Session["UserId"];
                    domain.CreatedByName = Session["UserFullName"].ToString();
                    domain.ModifiedDT = DateTime.Now;
                    domain.ModifiedById = (Guid)Session["UserId"];
                    domain.ModifiedByName = Session["UserFullName"].ToString();

                    //Update the BusinessUnit record
                    BusinessUnit bu = domain.PrimaryBusinessUnit;
                    bu.DomainId = domain.DomainId;
                    bu.IsDroppedYN = "N";
                    bu.CreateDT = DateTime.Now;
                    bu.CreatedById = (Guid)Session["UserId"];
                    bu.CreatedByName = Session["UserFullName"].ToString();
                    bu.ModifiedDT = DateTime.Now;
                    bu.ModifiedById = (Guid)Session["UserId"];
                    bu.ModifiedByName = Session["UserFullName"].ToString();

                    // Address
                    Address addr = bu.Address;
                    bu.MainAddressId = addr.AddressId;

                    // Make the BU Address Association
                    CoreEntities core = new CoreEntities();
                    Guid MainAddressTag = core.Tags.First(m => (m.TagName == "Main Address" && m.BusinessUnitId == null)).TagId;
                    BUAddress buaddress = new BUAddress();
                    buaddress.AddressId = (Guid)bu.MainAddressId;
                    buaddress.BusinessUnitId = bu.BusinessUnitId;
                    buaddress.TagId = MainAddressTag;
                    buaddress.IsPublicYN = "Y";

                    // Save the changes
                    core.AddToDomains(domain);
                    core.SaveChanges();
                    core.AddToBusinessUnits(bu);
                    core.AddToBUAddresses(buaddress);
                    BUHelper.UpdatePlugins(ref core, bu.BusinessUnitId, bu.PluginIds);
                    core.SaveChanges();
                    return RedirectToAction("Index");
                }
                else
                    return View(domain);
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", Tools.ExceptionMessage(e));
                CoreEntities core = new CoreEntities();
                ViewBag.Themes = core.Themes.Where(m => m.IsForMobileYN == "N").ToList();
                ViewBag.MobileThemes = core.Themes.Where(m => m.IsForMobileYN == "Y").ToList();
                return View(domain);
            }
        }
        
        //
        // GET: /Domain/Edit/5

        [Permission("Can Create/Delete Domain, Can Modify Domain")]
        public ActionResult Edit(Guid id)
        {
            CoreEntities core = new CoreEntities();
            Domain domain = core.Domains.First(d => d.DomainId == id);
            domain.PrimaryBusinessUnit = domain.BusinessUnits.First(m => m.BusinessUnitId == domain.PrimaryBU);
            ViewBag.Themes = core.Themes.Where(m => m.IsForMobileYN == "N").ToList();
            ViewBag.MobileThemes = core.Themes.Where(m => m.IsForMobileYN == "Y").ToList();
            BusinessUnit bu = domain.PrimaryBusinessUnit;
            BUHelper.PopulatePlugins(core, ref bu, false);
            return View(domain);
        }

        //
        // POST: /Domain/Edit/5

        [HttpPost]
        [Permission("Can Create/Delete Domain, Can Modify Domain")]
        public ActionResult Edit(Guid id, Domain domain, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                Tools.DebugInfo("Domain Edit: Entered method.");
                CoreEntities domainbu = new CoreEntities();
                Domain upddomain = domainbu.Domains.First(d => d.DomainId == id);
                Tools.DebugInfo("Domain Edit: Updating Model.");
                UpdateModel( upddomain, collection.ToValueProvider());
                upddomain.ModifiedDT = DateTime.Now;
                upddomain.ModifiedById = (Guid)Session["UserId"];
                upddomain.ModifiedByName = Session["UserFullName"].ToString();
                Tools.DebugInfo("Domain Edit: Updating BU.");
                BusinessUnit bu = upddomain.BusinessUnits.First(m => m.BusinessUnitId == upddomain.PrimaryBU);
                bu.BusinessUnitName = upddomain.PrimaryBusinessUnit.BusinessUnitName;
                bu.Phone = upddomain.PrimaryBusinessUnit.Phone;
                bu.Fax = upddomain.PrimaryBusinessUnit.Fax;
                bu.Email = upddomain.PrimaryBusinessUnit.Email;
                Tools.DebugInfo("Domain Edit: Updating Address.");
                Address naddr = upddomain.PrimaryBusinessUnit.Address;
                bu.Address.Line1 = naddr.Line1;
                bu.Address.Line2 = naddr.Line2;
                bu.Address.City = naddr.City;
                bu.Address.State = naddr.State;
                bu.Address.PostalCode = naddr.PostalCode;
                bu.Address.Country = naddr.Country;
                Tools.DebugInfo("Domain Edit: Updating Plugins.");
                BUHelper.UpdatePlugins(ref domainbu, upddomain.PrimaryBU, upddomain.PrimaryBusinessUnit.PluginIds);
                Tools.DebugInfo("Domain Edit: Saving Changes.");
                domainbu.SaveChanges();
                Tools.DebugInfo("Domain Edit: Changing Theme in use.");
                if (((Guid)Session["DomainId"]).Equals(upddomain.DomainId))
                {
                    if (((Theme)Session["Theme"]).ThemeId.CompareTo(upddomain.ThemeId) != 0)
                    {
                        Session["Theme"] = domainbu.Themes.First(model => model.ThemeId == upddomain.ThemeId);
                    }
                }
                Tools.DebugInfo("Domain Edit: All completed, redirecting.");
                return RedirectToAction("Index");
            }
            catch(Exception e)
            {
                ModelState.AddModelError("", Tools.ExceptionMessage(e));
                Tools.DebugInfo(e.Source);
                Tools.DebugInfo(e.StackTrace);
                CoreEntities core = new CoreEntities();
                ViewBag.Themes = core.Themes.Where(m => m.IsForMobileYN == "N").ToList();
                ViewBag.MobileThemes = core.Themes.Where(m => m.IsForMobileYN == "Y").ToList();
                return View(domain);
            }
        }

        //
        // GET: /Domain/Delete/5

        [Permission("Can Create/Delete Domain")]
        public ActionResult Delete(Guid id)
        {
            CoreEntities domainbu = new CoreEntities();
            Domain domain = domainbu.Domains.First(d => d.DomainId == id);
            domain.PrimaryBusinessUnit = domain.BusinessUnits.First(m => m.BusinessUnitId == domain.PrimaryBU);
            BusinessUnit bu = domain.PrimaryBusinessUnit;
            BUHelper.PopulatePlugins(domainbu, ref bu, true);
            ViewBag.MobileTheme = domain.MobileThemeId.HasValue ? domainbu.Themes.First(m => m.ThemeId == domain.MobileThemeId).Name : "";
            return View(domain);
        }

        //
        // POST: /Domain/Delete/5

        [HttpPost]
        [Permission("Can Create/Delete Domain")]
        public ActionResult Delete(Guid id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
                CoreEntities domainbu = new CoreEntities();
                Domain domain = domainbu.Domains.First(d => d.DomainId == id);
                domain.IsDroppedYN = "Y";
                domain.ModifiedDT = DateTime.Now;
                domain.ModifiedById = (Guid)Session["UserId"];
                domain.ModifiedByName = Session["UserFullName"].ToString();
                domainbu.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", Tools.ExceptionMessage(e));
                return View();
            }
        }

    }
}
